import { useEffect, useState, useRef } from 'react';
import { Pagination, Skeleton } from 'antd';
import loadable from '@loadable/component';

import { EE, RELOAD_COMMENT } from '@/utils/emitter';
import { getCommentList, likeComment } from '@/service/comments';
import styles from './index.module.scss';

const CommentItem = loadable(() => import('./CommentItem'), { fallback: <Skeleton.Input style={{padding:6}} active/> });
const CommentForm = loadable(() => import('./CommentForm'), { fallback: <Skeleton.Button style={{padding:6}} block active/> });

export default props => {
    const initState = () => ({
        loading: false,
        pageNo: 1,
        pageSize: 10,
        total: 0,
        dataList: [],

        objectId: '',
    });
    const [state, setState] = useState(initState);
    const objectId = useRef(props.id);

    // 请求评论列表
    const getCommentListData = async (options={}) => {
        const { pageNo, pageSize } = state;
        const postData = {
            objectId: objectId.current,
            pageNo,
            pageSize,
            ...options,
        };

        setState(o => ({...o, loading: true}));
        try{
            const [res, err] = await getCommentList(postData);
            if(OK_CODE === res?.code) {
                const {records, current, total, size} = res.data || {};

                setState(o => ({
                    ...o,
                    dataList: records || [],
                    pageNo: current || 1,
                    total: total || 0,
                    pageSize: size,
                    objectId: postData.objectId,
                }));
            }
        }finally{
            setState(o => ({...o, loading: false}));
        };
    };

    // 渲染评论列表
    const renderComment = (data=[]) => {
        return (data || []).map(item => {
            return (
                <div key={item.id} className={`${styles['comment-row']} ${item.parentId ? styles['indent'] : ''}`}>
                    <CommentItem
                        id={state.objectId}
                        dataSource={item}
                        onOk={getCommentListData}
                        onCancel={() => {}}
                    />
                    {
                        Array.isArray(item.children) && item.children.length ?
                            renderComment(item.children)
                            :
                            null
                    }
                </div>
            );
        });
    };

    // 切换分页
    const changePagination = (pageNo, pageSize) => {
        getCommentListData({pageNo, pageSize});
    };

    useEffect(() => {
        const { id } = props;
        objectId.current = id;

        if(id) getCommentListData({objectId: id});
    }, [props.id]);
    useEffect(() => {
        EE.on(RELOAD_COMMENT, () => {
            getCommentListData({pageNo: 1, objectId: objectId.current});
        });

        return () => {
            EE.off(RELOAD_COMMENT);
        };
    }, []);

    return (
        <div className={styles['container']}>
            <div className={styles['header']}>评论区</div>
            <div className={styles['comment-form']}>
                <CommentForm id={props.id} onOk={() => EE.emit(RELOAD_COMMENT)}/>
            </div>
            <div className={styles['comment-list']}>
                {
                    !state.loading && !(state.dataList || []).length ?
                        <div className={styles['empty']}>
                            <img src="/images/nodata.svg" alt="暂无数据" />
                        </div>
                        :
                        renderComment(state.dataList || [])
                }
            </div>
            <div className={styles['pagination']}>
                <Pagination
                    current={state.pageNo}
                    total={state.total}
                    pageSize={state.pageSize}
                    hideOnSinglePage={true}
                    onChange={changePagination}
                />
            </div>
        </div>
    )
}
